using System;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;

namespace TimerA1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // discovery endpoint
            var client = new HttpClient();
            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000/");

            if (disco.IsError)
            {
                Console.WriteLine("disco Error: " + disco.Error);
                return;
            }
            // request access token
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,
                ClientId = "TimerA1",
                ClientSecret = "secret_TimerA1",
                Scope = "BackA1"
            });
            if (tokenResponse.IsError)
            {
                Console.WriteLine("tokenResponse Error: " + tokenResponse.Error);
                return;
            }

            // call Identity Resource API
            var apiClient = new HttpClient();
            apiClient.SetBearerToken(tokenResponse.AccessToken);
            {
                var response = await apiClient.GetAsync("http://127.0.0.1:5555/Test1");
                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine("response Error: " + response.StatusCode);
                }
                else
                {
                    var content = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(content);
                }
            }
            {

                //var response = await apiClient.GetAsync("http://127.0.0.1:5555/Test2");
                //if (!response.IsSuccessStatusCode)
                //{
                //    Console.WriteLine("response Error: " + response.StatusCode);
                //}
                //else
                //{
                //    var content = await response.Content.ReadAsStringAsync();
                //    Console.WriteLine(content);
                //}
            }
            Console.WriteLine("Hello World!");

            Console.ReadKey();

        }
    }
}
